//
//  ComposeView.swift
//  Weibo
//
//  Created by 郑克哥哥 on 2017/8/1.
//  Copyright © 2017年 郑克哥哥. All rights reserved.
//

import UIKit
import pop
//罩层视图
class ComposeView: UIView {
    
    //目标控制器
    var target: UIViewController?
    
    //存储6个按钮的容器
    private lazy var composeButtonArr: [ComposeButton] = [ComposeButton]()
    //撰写菜单模型数组
    private lazy var composeMenuArray:[ComposeMenu] = {
        
        let modelArr = self.loadComposePlistData()
        
        return modelArr
    }()
    
    //默认就是毛玻璃模糊效果
    private var toolBar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight))
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        loadComposePlistData()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
    
        addSubview(toolBar)
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        addChlidButton()
        //执行动画
        startPopSpringAnimation(isUp: true)
        
    }
    
    //添加菜单按钮
    private func addChlidButton(){
        //按钮的宽度
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        
        //按钮的间距
        let buttonMargin: CGFloat = (width - 4 * buttonWidth) / 5
        for i in 0..<composeMenuArray.count {
            //列索引
            let colIndex = i % 4
            //行索引
            let rowIndex = i / 4
            let button = ComposeButton()
            //设置tag值,获取tag值对应的模型
            button.tag = i
            button.addTarget(self, action: #selector(clickButton(btn:)), for: .touchUpInside)
            //计算x公式:列索引 * 按钮的宽度 + (列索引 + 1) * 按钮的间距
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            //获取每个模型
            let model = composeMenuArray[i]
            button.setImage(UIImage(named:model.icon!), for: .normal)
            button.setTitle(model.title!, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.setTitleColor(UIColor.gray, for: .normal)
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            addSubview(button)
            //添加到撰写数组中
            composeButtonArr.append(button)
        }
    }
    
    //点击按钮事件
    @objc private func clickButton(btn:UIButton) {
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for button in self.composeButtonArr{
                button.alpha = 0.3
                
                if button == btn {
                    //放大
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    //缩小
                    button.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
                }
            }
           
        }) { (_) in
            UIView.animate(withDuration: 0.25, animations: { 
                for button in self.composeButtonArr{
                    button.alpha = 1
                    //恢复
                    button.transform = CGAffineTransform.identity
                }
                
            }, completion: { (_) in
                print("弹出发微博界面")
                //通过类名字符串获取类的实例
                //1.通过类名获取Class,自己定义的类获取对应的类名的时候会有命名空间
                //在使用构造函数的时候,需要转换成指定类型
                let model = self.composeMenuArray[btn.tag]
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
                //2.通过class创建实例
                let VC = classType.init()
                //3.创建导航控制器
                let nav = ZKNavgationController(rootViewController: VC)
                
                //弹出控制器
                self.target?.present(nav, animated: true, completion: {
                    //移除当前视图
                    self.removeFromSuperview()
                    
                })
                
            })
        }
        
        
        
        
    }
    
    //执行弹簧动画
    private func startPopSpringAnimation(isUp: Bool){
        
        if isUp == false {
            //reversed:数组反转
            composeButtonArr = composeButtonArr.reversed()
        }
        
        for (i,ComposeButton) in composeButtonArr.enumerated() {
            
            //创建动画对象
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //动画目的地
            if isUp {
                animation?.toValue = CGPoint(x: ComposeButton.centerX, y: ComposeButton.centerY - 350)
            }else{
                animation?.toValue = CGPoint(x: ComposeButton.centerX, y: ComposeButton.centerY + 350)
            }
            
            //[0-20] 弹力 越大则震动幅度越大
            animation?.springBounciness = 10
            //[0-20] 速度越大则动画结束越快
            animation?.springSpeed = 10
            //时间间隔
            animation?.beginTime = CACurrentMediaTime() + Double(i) * 0.02
            
            ComposeButton.pop_add(animation, forKey: nil)
            
            
        }
        
        
        
    }
    
    //点击的时候,移除罩层
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //向下的pop动画
        startPopSpringAnimation(isUp: false)
        //回到主线程移除视图
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
            self.removeFromSuperview()
        }
        
    }
    
    //显示罩层
    func show(target: UIViewController){
        //记录目标控制器
        self.target = target
        //添加到目标控制器
        target.view.addSubview(self)
        
//        let window = UIApplication.shared.keyWindow!
//        
//        window.addSubview(self)
        
    }
    
    //读取plist文件数据
    private func loadComposePlistData()-> [ComposeMenu]{
        //文件路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)
        //加载文件数据
        let dictArr = NSArray(contentsOfFile: path!)!
        
        let composeMenuArr = NSArray.yy_modelArray(with: ComposeMenu.self, json: dictArr) as! [ComposeMenu]
        
        return composeMenuArr
        
    }

}
